/*
 * =============================================================================
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <eirikb@google.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Eirik Brandtzæg
 * =============================================================================
 */
package no.eirikb.roboco.terminal.command;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.roboco.terminal.element.CommandBoxElement;
import no.eirikb.roboco.terminal.element.Element;

/**
 *
 * @author eirikb
 * @author <a href="mailto:eirikb@google.com">eirikb@google.com</a>
 */
public class CAT extends Command {

    private final String[] HELP = {"CAT IS USED TO VIEW FILES.",
        "CAT IS BASED ON ISOLATION LEVELS;",
        "LEVEL -1: NO ACCESS",
        "LEVEL 0: READ ALL ./TXT/*",
        "LEVEL 1: READ ALL FILES ON TERMINAL",
        "LEVEL 2: READ ALL FILES ON ALL TERMINALS",
        "LEVEL 3: READ ALL FILES ANYWHERE"};

    public CAT(Element element, StringTokenizer stringTokenizer) {
        super(element, stringTokenizer);
    }

    public void execute() {
        if (getStringTokenizer().hasMoreTokens()) {
            String fileName = getStringTokenizer().nextToken();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(
                        new FileInputStream(getElement().getTerminal().getFile().
                        getAbsolutePath() + File.separator + "txt" +
                        File.separator + fileName)));
                String line;
                while ((line = reader.readLine()) != null) {
                    getElement().sendLine(line);
                }
            } catch (IOException ex) {
                getElement().sendLine("FILE NOT FOUND");
                Logger.getLogger(CommandBoxElement.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(CommandBoxElement.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            getElement().sendLine("MUST SPECIFY A FILE");
        }
    }

    public String[] getHelp() {
        return HELP;
    }
}
